package com.gitee.kamismile.stone.basic.data.domain.sysDep.service.impl;

import com.gitee.kamismile.stone.basic.data.domain.sysDep.repository.entity.SysDep;
import com.gitee.kamismile.stone.basic.data.domain.sysDep.service.ISysDepDomainService;
import com.gitee.kamismile.stone.basic.data.infrastructure.enums.DepErrorEnum;
import com.gitee.kamismile.stone.basic.data.infrastructure.repository.r2Repository.sysDep.repository.SysDepRepository;
import com.gitee.kamismile.stone.basic.data.infrastructure.utils.PageQueryBuilder;
import com.gitee.kamismile.stone.commmon.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import reactor.core.publisher.Mono;

@Service
public class SysDepDomainServiceImpl implements ISysDepDomainService {
    @Autowired
    private R2dbcEntityTemplate template;

    @Autowired
    private SysDepRepository sysDepRepository;

    @Override
    public Mono<SysDep> saveOrUpdate(SysDep sysDep) {
        return sysDepRepository.save(sysDep);
    }

    @Override
    public Mono<Void> deleteDepById(Integer nSysDepId) {
        return sysDepRepository.deleteById(nSysDepId);
    }

    @Override
    public Mono<Page<SysDep>> findDepPage(int page, int size, Criteria criteria) {
        Pageable pageable = PageRequest.of(page, size);
        return new PageQueryBuilder<>(template, SysDep.class)
                .where(criteria)
                .pageable(pageable)
                .apply();    }


    @Override
    public Mono<SysDep> findDepById(Integer nSysDepId, Integer nTenantId) {
        Assert.notNull(nSysDepId,DepErrorEnum.DepNotNull.getMessage());

        SysDep example = new SysDep();
        example.setnSysDepId(nSysDepId);
        example.setnTenantId(nTenantId);
        return sysDepRepository.findOne(Example.of(example));
    }

    @Override
    public Mono<SysDep> findAndCheckDepById(Integer nSysDepId, Integer nTenantId) {
        return findDepById(nSysDepId, nTenantId)
                .switchIfEmpty(Mono.defer(() -> Mono.error(
                        new BusinessException(
                        DepErrorEnum.DepNotFound.getCode(),
                                DepErrorEnum.DepNotFound.getMessage()
                                ))));
    }

    @Override
    public Mono<Integer> modifyIslast(Integer nSysDepId, Integer nTenantId) {
        Assert.notNull(nSysDepId,DepErrorEnum.DepNotNull.getMessage());

        return sysDepRepository.modifyIslast(nSysDepId, nTenantId);
    }
}
